import json
import os.path

from rest_framework.decorators import api_view
from django.http.response import HttpResponse

from .qa.q_a import encode_sentence, get_match_question, load_q_a_data

module_dir = os.path.dirname(__file__)


@api_view(['GET'])
def get_answer(request):
    question = request.query_params.get('q', None)
    input_encode = encode_sentence(question)
    match_keys = get_match_question(input_encode)
    file_path = os.path.join(module_dir, 'data/q_a.json')
    q_a_data = {}
    if not q_a_data:
        q_a_data = load_q_a_data(file_path)
    r = []
    if match_keys:
        for k in match_keys:
            q_a = {"question": k}
            if k in q_a_data.keys():
                q_a["answer"] = q_a_data[k]
                r.append(q_a)
    return HttpResponse(json.dumps(r, ensure_ascii=False), content_type='application/json')
